package iot.wlink.network.devices.shadows;

import cn.hutool.core.util.ObjectUtil;
import iot.wlink.network.devices.shadows.block.ShadowState;

import iot.wlink.network.payload.up.PointValue;
import lombok.Data;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : willian fu
 * @date : 2021/8/19
 */
@Data
public class DeviceShadow {

    private ShadowStateChangeListener listener;

    private String uid;

    //设备状态
    private ShadowState state;

    //最近更新时间
    private Date updated;

    //版本号，递增
    private Long version;

    public void regChangeListener(ShadowStateChangeListener listener){
        this.listener = listener;
    }

    public void upActual(String uid, Map<String, PointValue> payload){
        Map<String, PointValue> collect = payload.entrySet().stream()
                .filter(p -> {
                    PointValue stateValue = state.getActual().get(p.getKey());
                    if (p.getValue().getValue().equals(stateValue.getValue())) {
                        return true;
                    }
                    //更新值
                    p.getValue().loadTime();
                    state.getActual().put(p.getKey(), p.getValue());
                    return false;
                })
                .collect(Collectors.toMap(
                        e -> e.getKey(),
                        e -> e.getValue()
                ));
        if (ObjectUtil.isNotNull(listener)){
            listener.change(uid, collect);
        }
    }

    public void upDesired(Map<String, PointValue> payload){
        payload.forEach((k, v) -> v.loadTime());
        state.getDesired().putAll(payload);
    }
}
